package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:ahang
 * @create:2022-07-24 11:41
 * @Description:
 */
@Service(interfaceClass = DictService.class)
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

    @Autowired
    private DictDao dictDao;

    @Override
    protected BaseDao<Dict> getEntityDao() {
        return dictDao;
    }

    /*
    * [
    * {
    *  id:''
    *  name:''
    *  isParent:''
    * },
    * {...}
    * ]
    * */
    @Override
    public List<Map<String, Object>> findZnodes(Long id) {
        //调用Dao查询指定的id的子元素列表
        List<Dict> dictList = dictDao.findListByParentId(id);

        //将List<Dict>转换为List<Map>,前台zTree需要的json格式
        List<Map<String,Object>> zNodes = new ArrayList<>();

        for (Dict dict : dictList) {
            Map<String,Object> zNode = new HashMap<>();
            zNode.put("id",dict.getId());
            zNode.put("name",dict.getName());
            int count = dictDao.countIsParent(dict.getId());
            zNode.put("isParent",count>0?true:false);
            zNodes.add(zNode);
        }
        return zNodes;
    }

    /**
     * 根据编码获取子节点数据列表（不需要进行封装）
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        //根据dictcode获取dict对象的数据
        Dict dict = dictDao.getByDictCode(dictCode);
        if(null == dict) return null;
        //根据dict对象获取id
        Long id = dict.getId();
        //根据id查询所有下级元素
        List<Dict> dictList = dictDao.findListByParentId(id);
        return dictList;
    }

    /**
     * 根据上级id获取子节点数据列表(不需要进行封装)
     * @param parentId
     * @return
     */
    @Override
    public List<Dict> findListByParentId(Long parentId) {
        List<Dict> dictList = dictDao.findListByParentId(parentId);
        return dictList;
    }

    @Override
    public String getNameById(Long id) {
        return dictDao.getNameById(id);
    }
}
